#! user/bin/python
# -*- coding: utf-8 -*-

"""
Created on 2021/8/19 14:44

@File: 派生服务器_thread-server.py
@Author: LT
@Description: Use of this module
"""
import os
import sys
import time
from socket import *
import threading

myHost = ""
myPort = 50007

sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((myHost, myPort))
sockobj.listen(5)


def now():
    return time.ctime(time.time())


def handleClient(connection):
    print("Child:", os.getpid())
    time.sleep(5)
    while True:
        data = connection.recv(1024)
        if not data:
            break
        reply = "Echo=>%s at %s" % (data, now())
        connection.send(reply.encode())
    connection.close()
    # sys.exit(0)                                         # os._exit(0)用不了，先用这个代替


def dispatcher():
    """持续监听，等待客户端连接进来，知道进程被终止"""
    while True:
        connection, address = sockobj.accept()
        print("Server connected by", address, end="")
        print("at", now())
        thread = threading.Thread(target=handleClient, args=(connection,))
        thread.start()


if __name__ == '__main__':
    print("Parent:", os.getpid())
    sockobj = socket(AF_INET, SOCK_STREAM)
    sockobj.bind((myHost, myPort))
    sockobj.listen(5)
    dispatcher()
